package book.chapter05.$5_3_7;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.CountDownLatch;

//使用无权限信息的ZooKeeper会话访问含权限信息的数据节点
public class AuthSample_Get implements Watcher {

    final static String PATH = "/zk-book-auth_test1";
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        /**
         *   new出ZooKeeper实例时只是建立了与服务端之间的会话，
         *   此时TCP连接可能还未建立完成，如果这时发出ZooKeeper操作命令的确会出现连接丢失异常，
         *   虽然这种概率相对较小。
         */
//        ZooKeeper zookeeper1 = new ZooKeeper("192.168.48.133:2181",5000,null);
        ZooKeeper zookeeper1 = new ZooKeeper("192.168.48.133:2181",5000,new AuthSample_Get());
        /**
         * 因此这里做一个 await ，加watcher 监听事件
         */
        connectedSemaphore.await();
        zookeeper1.addAuthInfo("digest", "foo:true".getBytes());

        zookeeper1.create( PATH, "init".getBytes(), Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL );

//        ZooKeeper zookeeper2 = new ZooKeeper("192.168.48.133:2181",50000,null);
        ZooKeeper zookeeper2 = new ZooKeeper("192.168.48.133:2181",50000,new AuthSample_Get());
        zookeeper2.getData( PATH, false, null );
    }

    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            connectedSemaphore.countDown();
        }
    }
}